import { Form,Icon,Input, Select,Button, Radio,InputNumber } from "antd";
import React from "react";
import styles from "../../index.less"
import JudgeConditions from "./judgeConditions";
import { formDictionaryColumn, formDictionaryColumnTree, formFieldInfo, formFieldList } from "@/services/formInteraction";
import { fetchApiListById } from "@/services/basiccapacity";
import moment from "moment";

class JudgeNode extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      conditionList:[
        [
          {
            judgeType:"",//0:字段 1:api
            judgeValue:"",//字段名的id/api响应字段的id
            apiId:"",//api名称的id
            conditionType:"",//0:等于 1：不等于 2：大于 3：小于 :4：为空 5：不为空 6：包含 7：不包含
            fieldType:"",//0：常量 1：变量
            conditionValue:""//输入的值
          }
        ]
      ],
      fieldList:[],
      apiList:[],
      responseList:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initForm = data => {
    this.getFieldsList()
    this.getApiList()
    const { form:{setFieldsValue} } = this.props
    console.log(data.label);
    setFieldsValue({label:data.label})
    if(data.data){
      try{
        const conditionList = JSON.parse(data.data.judge.condition)
        this.setState({
          conditionList
        })
      }catch(e){}
    }
  }

  getFieldsList = async () => {
    const { formId } = this.props;
    const res = await formFieldList({formId});
    this.setState({
      fieldList:res
    })
  }

  getApiList = async () => {
    const res = await fetchApiListById({current:1,size:9999999999999999,type:1})
    this.setState({
      apiList:res.records
    })
  }

  changeJudgeType = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex] = {
      judgeType:value,//0:字段 1:api
      judgeValue:"",//字段名的id/api响应字段的id
      apiId:"",//api名称的id
      conditionType:"",//0:等于 1：不等于 2：大于 3：小于 :4：为空 5：不为空 6：包含 7：不包含
      fieldType:"",//0：常量 1：变量
      conditionValue:""//输入的值
    };

    this.setState({
      conditionList:list
    })
  }

  changeJudgeValue = async (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].judgeValue = value;
    list[conIndex][itemIndex].conditionType = ''
    list[conIndex][itemIndex].fieldType = ''
    list[conIndex][itemIndex].conditionValue = ''
    //用于前端转换多选项的字段
    list[conIndex][itemIndex].conditionValueMultiple = []
    //用于前端转换开关字段
    list[conIndex][itemIndex].conditionValueSwitch = false
    //用于前端转换日期/时间字段
    list[conIndex][itemIndex].conditionValueDateTime = null
    //用于前端转换级联字段
    list[conIndex][itemIndex].conditionValueCascader = []

    //根据选择的字段ID 获取字段详情 用于展示不同字段类型 不同输入框
    const res = await formFieldInfo({id:value})
    list[conIndex][itemIndex].fieldInfo = res
    //选项 且非开关 且 选项值为数据字典类型 则需要通过接口获取 选项列表值
    if(res.componentType == 3 && res.optionRange == 0 && res.componentStyle != 3){
      const res2 = await formDictionaryColumn({id:res.dictionaryId,name:res.optionContent ? res.optionContent[0] : ''})
      list[conIndex][itemIndex].fieldInfo.optionList = res2
    }
    //级联 获取选项数据
    if(res.componentType == 5){
      const res3 = await formDictionaryColumnTree({id:res.dictionaryId,headerList:res.columnValue})
      list[conIndex][itemIndex].fieldInfo.cascaderList = res3
    }
    this.setState({
      conditionList:list
    })
  }

  changeConditionType = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionType = value

    this.setState({
      conditionList:list
    })
  }

  changeFieldType = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].fieldType = value

    this.setState({
      conditionList:list
    })
  }

  changeConditionValue = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionValue = value

    this.setState({
      conditionList:list
    })
  }

  changeApiId = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].apiId = value;
    //获取api对应的响应字段

    list[conIndex][itemIndex].judgeValue = '';

    this.setState({
      conditionList:list
    })
  }

  removeItem = (conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    const itemList = list[conIndex]
    const newList = []
    for(const i in itemList){
      if(i!= itemIndex){
        newList.push(itemList[i])
      }
    }
    list[conIndex] = newList
    this.setState({
      conditionList:list
    })
  }

  addItem = conIndex => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex].push({
      judgeType:'',//0:字段 1:api
      judgeValue:"",//字段名的id/api响应字段的id
      apiId:"",//api名称的id
      conditionType:"",//0:等于 1：不等于 2：大于 3：小于 :4：为空 5：不为空 6：包含 7：不包含
      fieldType:"",//0：常量 1：变量
      conditionValue:""//输入的值
    })
    this.setState({
      conditionList:list
    })
  }

  addCondition = () => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list.push([{
      judgeType:'',//0:字段 1:api
      judgeValue:"",//字段名的id/api响应字段的id
      apiId:"",//api名称的id
      conditionType:"",//0:等于 1：不等于 2：大于 3：小于 :4：为空 5：不为空 6：包含 7：不包含
      fieldType:"",//0：常量 1：变量
      conditionValue:""//输入的值
    }])
    this.setState({
      conditionList:list
    })
  }

  removeCondition = index => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    const newList = []
    for(const i in list){
      if(i!= index){
        newList.push(list[i])
      }
    }
    this.setState({
      conditionList:newList
    })
  }

  checkSave = () => {
    let { conditionList } = this.state;
    this.props.form.validateFields((error,values) => {
      if(!error){
        let obj = {
          label:values.label,
          data:{
            judge:{
              condition:JSON.stringify(conditionList)
            }
          }
        }
        this.props.doSave(obj)
      }
    })
  }

  //修改复选的值
  changeConditionValueMultiple = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionValueMultiple = value

    list[conIndex][itemIndex].conditionValue = value.join('\n')

    this.setState({
      conditionList:list
    })
  }

  //修改开关的值
  changeConditionValueSwitch = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionValueSwitch = value

    list[conIndex][itemIndex].conditionValue = value+''

    this.setState({
      conditionList:list
    })
  }

  //修改时间-年-面板关闭打开
  handleOpenChange = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].yearOpen = value
    if(list[conIndex][itemIndex].conditionValueDateTime && typeof(list[conIndex][itemIndex].conditionValueDateTime) == 'string'){
      list[conIndex][itemIndex].conditionValueDateTime = moment(list[conIndex][itemIndex].conditionValueDateTime)
    }
    this.setState({
      conditionList:list
    })
  }

  //修改时间-年-面板切换
  handlePanelChange = (value,conIndex,itemIndex,dateType) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionValueDateTime = value
    list[conIndex][itemIndex].conditionValue = this.formatDateTime(value,dateType)
    list[conIndex][itemIndex].yearOpen = false
    console.log(list[conIndex][itemIndex]);
    this.setState({
      conditionList:list
    })
  }

  changeDateValue = (value,conIndex,itemIndex,dateType) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionValueDateTime = value
    list[conIndex][itemIndex].conditionValue = this.formatDateTime(value,dateType)
    this.setState({
      conditionList:list
    })
  }

  changeConditionValueCascader = (value,conIndex,itemIndex) => {
    const list = JSON.parse(JSON.stringify(this.state.conditionList));
    list[conIndex][itemIndex].conditionValueCascader = value
    list[conIndex][itemIndex].conditionValue = value.toString()
    this.setState({
      conditionList:list
    })
  }

  formatDateTime = (date,dateType) => {
    const currentDay = moment().format("YYYY-MM-DD")
    let dateFormat = 'YYYY-MM-DD HH:mm:ss'
    switch(dateType){
      case 0 :
        dateFormat = 'YYYY';
        break;
      case 1:
        dateFormat = 'YYYY-MM'
        break;
      case 2:
        dateFormat = 'YYYY-MM-DD';
        break;
      case 3:
        dateFormat = 'YYYY-MM-DD HH';
        break;
      case 4:
        dateFormat = 'YYYY-MM-DD HH:mm';
        break;
      case 5:
        dateFormat = 'YYYY-MM-DD HH:mm:ss';
        break;
      case 6:
        dateFormat = ' HH:mm';
        break;
      case 7:
        dateFormat = ' HH:mm:ss';
        break;
      default:
        dateFormat = 'YYYY-MM-DD HH:mm:ss'
        break;
    }
    return moment(date).format(dateFormat)
  }

  render(){
    const { conditionList,fieldList ,apiList,responseList} = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 },
      },
    };
    const formItemSpecial = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
    };
    const conditionStyle = {
      background:'#3e5bff',
      color:'#ffffff',
      borderRadius:'50%',
      padding:'2px 5px',
      verticalAlign: 'middle'
    }
    const dividerStyle = {
      display:'inline-block',
      verticalAlign: 'middle',
      width:'calc(100% - 50px)',
      height:'1px',
      background:'#E8E8E8'
    }
    const deleteStyle = {
      marginLeft:10,
      cursor:'pointer'
    }
    const inlineFormItem = {display:"inline-block",marginBottom:0}
    return(
      <Form {...formItemLayout}>
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />基本信息</div>
        <Form.Item label="节点名称">
          {
            getFieldDecorator("label",{rules:[{required:true,message:"请输入"}]})(
              <Input className={styles.inputItem} />
            )
          }
        </Form.Item>
        <Form.Item {...formItemSpecial}>
          {
            conditionList.map((con,index) => {
              return (
                <div key={index}>
                  {
                    index != 0 ? <div><span style={conditionStyle}>或</span><span style={dividerStyle}></span><Icon type="close" style={deleteStyle} onClick={() => this.removeCondition(index)} /></div> : ''
                  }
                  <div key={index} style={{paddingLeft:24}}>
                    {
                      con.map((item,itemIndex) => {
                        return (
                          <div index={itemIndex}>
                            {
                              itemIndex != 0 ? <div><span style={conditionStyle}>且</span></div> : ''
                            }
                            <JudgeConditions
                              con={con}
                              index={index}
                              item={item}
                              itemIndex={itemIndex}
                              changeJudgeType={this.changeJudgeType}
                              changeJudgeValue={this.changeJudgeValue}
                              changeConditionType={this.changeConditionType}
                              changeFieldType={this.changeFieldType}
                              changeApiId={this.changeApiId}
                              changeConditionValue={this.changeConditionValue}
                              removeItem={this.removeItem}
                              fieldList={fieldList}
                              apiList={apiList}
                              responseList={responseList}
                              changeConditionValueMultiple={this.changeConditionValueMultiple}
                              changeConditionValueSwitch={this.changeConditionValueSwitch}
                              handleOpenChange={this.handleOpenChange}
                              handlePanelChange={this.handlePanelChange}
                              changeDateValue={this.changeDateValue}
                              changeConditionValueCascader={this.changeConditionValueCascader}
                            />
                          </div>
                        )
                      })
                    }
                    <Button type="link" icon="plus" onClick={() => this.addItem(index)}>添加条件</Button>
                  </div>
                </div>
              )
            })
          }
          <Button type="primary" icon="plus" ghost onClick={this.addCondition}>添加条件组</Button>
        </Form.Item>
        <Form.Item label=" " colon={false}>
          <Button type="primary" onClick={this.checkSave}>保存</Button>
        </Form.Item>
      </Form>
    )
  }
}

export default Form.create()(JudgeNode)